<?php

namespace App\Library\BearyChat;

use \Illuminate\Http\Request;

class BearyChat
{
    public static function send(string $message)
    {
        $message = bearychat()
            ->createMessage()
            ->text($message);

        dispatch(new BearyChatJob($message));
    }

    public static function error(\Throwable $throwable, array $context = [])
    {
        /** @var Request $request */
        $request = app('request');

        $traces = explode("\n", $throwable->getTraceAsString());
        foreach ($traces as &$row) {
            $row = str_replace(base_path(), '', $row);
        }
        $trace = implode("\n", array_slice($traces, 0, 15));

        $message = config('app.name') . "-异常报告\n\n";
        $message = $message . "**{$throwable->getMessage()}**\n------\n";
        $message = $message . "```\n{$trace}\n```\n\n";

        foreach (static::formatRequest($request) as $title => $text) {
            $message = $message . "**{$title}**\n------\n";
            $message = $message . "{$text}\n\n";
        }

        $message = $message . "**Context**\n------\n";
        $message = $message . static::formatArray($context) . "\n\n";

        $message = bearychat()
            ->createMessage()
            ->text($message)
            ->markdown();

        dispatch(new BearyChatJob($message));
    }

    protected static function formatRequest(Request $request)
    {
        if (is_null($request->route())) {
            return [];
        }

        $ret = collect();

        $ret->put('Url', $request->fullUrl());
        $ret->put('Data', static::formatArray($request->all()));

        return $ret->toArray();
    }

    protected static function formatArray(array $array, ?string $prefix = null)
    {
        $lines = [];

        foreach ($array as $key => $value) {
            if (!is_null($prefix)) {
                $key = "{$prefix}.{$key}";
            }

            if (is_array($value)) {
                $lines = array_merge($lines, static::formatArray($value, $key));
            } else {
                $lines[] = "**{$key}**: {$value}";
            }
        }

        if (is_null($prefix)) {
            return implode("\n", $lines);
        } else {
            return $lines;
        }
    }
}
